package cn.christ.com.mobilesafe.view.activity_process;

import android.content.Intent;
import android.text.format.Formatter;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.Toast;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.christ.com.mobilesafe.R;
import cn.christ.com.mobilesafe.common.BaseActivity;
import cn.christ.com.mobilesafe.common.utils.LogUtils;
import cn.christ.com.mobilesafe.common.utils.SPUtils;
import cn.christ.com.mobilesafe.common.utils.ServiceStatusUtils;
import cn.christ.com.mobilesafe.constant.Constants;
import cn.christ.com.mobilesafe.engine.ProcessProvider;
import cn.christ.com.mobilesafe.modle.ProcessInfo;
import cn.christ.com.mobilesafe.service.ScreenService;
import cn.christ.com.mobilesafe.view.activity_process.adapter.ProcessAdapter;
import cn.christ.com.mobilesafe.view.activity_process.dagger2.DaggerProcessManagerComponent;
import cn.christ.com.mobilesafe.view.activity_process.dagger2.ProcessManagerModule;
import cn.christ.com.mobilesafe.view.activity_process.presenter.ProcessManagerPresenter;
import cn.christ.com.mobilesafe.view.widgets.DesProgressView;
import cn.christ.com.mobilesafe.view.widgets.SettingItemView;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

/**
 * @author xiaozhao 进程管理
 */
public class ProcessManagerActivity extends BaseActivity {
    @BindView(R.id.dpv_process)
    DesProgressView dpvProcess;
    @BindView(R.id.dpv_ram)
    DesProgressView dpvRam;
    @BindView(R.id.lv_process)
    StickyListHeadersListView lvProcess;
    @BindView(R.id.arrow1)
    ImageView ivArrow1;
    @BindView(R.id.arrow2)
    ImageView ivArrow2;
    @BindView(R.id.handle)
    RelativeLayout handle;
    @BindView(R.id.content)
    LinearLayout content;
    @BindView(R.id.slidingDrawer)
    SlidingDrawer slidingDrawer;
    @BindView(R.id.siv_show_sys)
    SettingItemView sivShowSys;
    @BindView(R.id.siv_lock_clean_process)
    SettingItemView sivLockCleanProcess;

    private int allProcessCount;
    private boolean mIsChecked;
    private int totalCleanCount;
    private long totalCleanMemory;

    @Inject
    ProcessManagerPresenter presenter;

    private List<ProcessInfo> userInfos = new CopyOnWriteArrayList<ProcessInfo>();
    private List<ProcessInfo> sysInfos = new CopyOnWriteArrayList<ProcessInfo>();
    private ProcessAdapter processAdapter;

    @Override
    public int getLayoutRes() {
        return R.layout.activity_process_manager;
    }

    @Override
    public void initPresenter() {
        //dagger2注入
        DaggerProcessManagerComponent
                .builder()
                .processManagerModule(new ProcessManagerModule(this))
                .build().inject(this);
    }

    @Override
    public void initView() {
        mIsChecked = (boolean) SPUtils.get(Constants.SHOW_SYS, false);
        sivShowSys.setChecked(mIsChecked);
        initHeadProcessData();
        initHeadRamData();
        initContentData();

    }

    @Override
    public void initData() {

    }

    // 初始化进程的头部数据
    private void initHeadProcessData() {
        // 获取正在运行的进程数
        int runningAppProcesses = ProcessProvider.getRunningProcessCount(this);
        // 获取所有的进程数
        allProcessCount = ProcessProvider.getAllProcessCount(this);
        dpvProcess.setLeftType("正在运行" + runningAppProcesses + "个");
        dpvProcess.setRightType("所有进程" + allProcessCount + "个");
        dpvProcess.setProgress(runningAppProcesses * 100 / allProcessCount);
    }

    private void initHeadRamData() {
        dpvRam.setLeftType("占用内存" + presenter.getUsedMemory(this));
        dpvRam.setRightType("所有内存" + presenter.getAllMemory(this));
        LogUtils.d(presenter.getProgress(this) + "所有内存");
        dpvRam.setProgress(presenter.getProgress(this));
    }


    private void initContentData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 加载数据
                sysInfos = presenter.getSysInfos();
                userInfos = presenter.getUserInfos();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        processAdapter = new ProcessAdapter(ProcessManagerActivity.this, sysInfos, userInfos);
                        lvProcess.setAdapter(processAdapter);
                    }
                });
            }
        }).start();
    }

    @Override
    public void initListener() {
        lvProcess.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 更新属性的值（position）
                ProcessInfo processInfo = getProcessInfo(position);
                processInfo.isChecked = !processInfo.isChecked;
                Toast.makeText(getApplicationContext(), "postion:" + processInfo.isChecked + position,
                        Toast.LENGTH_SHORT).show();
                // 更新UI
                if (processAdapter != null) {
                    processAdapter.notifyDataSetChanged();
                }
            }
        });

        // SlidingDrawer:打开的时候，关闭的时候应该怎么知道？？？
        slidingDrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {
            @Override
            public void onDrawerOpened() {
                initDownArrow();
            }
        });

        slidingDrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {

            @Override
            public void onDrawerClosed() {
                // initUpAnim();
                initUpArrow();
            }
        });

    }

    @OnClick({R.id.iv_cleanAll, R.id.btn_selectAll, R.id.btn_reverseAll, R.id.siv_show_sys, R.id.siv_lock_clean_process})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.siv_show_sys:
                showSys();
                break;
            case R.id.siv_lock_clean_process:
                sivLockCleanProcess();
                break;
            case R.id.iv_cleanAll:
                cleanAll();
                break;
            case R.id.btn_selectAll:
                selectAll();
                break;
            case R.id.btn_reverseAll:
                reverseAll();
                break;
        }
    }

    private void sivLockCleanProcess() {
        Intent intent = new Intent(ProcessManagerActivity.this, ScreenService.class);
        if (ServiceStatusUtils.isServiceRunning(getApplicationContext(), ScreenService.class)) {
            // 假如服务开启了，点击的时候，关闭
            // 更新UI
            sivLockCleanProcess.setChecked(false);
            stopService(intent);
        } else {
            // 假如服务关闭了, 点击的额时候，开启
            // 更新UI
            sivLockCleanProcess.setChecked(true);
            startService(intent);
        }
    }

    private void showSys() {
        // 1 更新UI
        sivShowSys.toggle();
        // 2 设置sp的值
        mIsChecked = sivShowSys.isChecked();
        SPUtils.put(Constants.SHOW_SYS, true);
        // 3 刷新列表
        if (processAdapter != null) {
            processAdapter.notifyDataSetChanged();
        }
    }

    // 箭头向上的动画
    private void initUpAnim() {
        // 透明度的动画
        AlphaAnimation a1 = new AlphaAnimation(1, 0);
        a1.setDuration(1000);
        a1.setRepeatCount(-1);

        AlphaAnimation a2 = new AlphaAnimation(0, 1);
        a2.setDuration(1000);
        a2.setRepeatCount(-1);

        ivArrow1.startAnimation(a1);
        ivArrow2.startAnimation(a2);
    }

    private ProcessInfo getProcessInfo(int position) {
        ProcessInfo processInfo = null;
        if (position < userInfos.size()) {
            processInfo = userInfos.get(position);
        } else {
            processInfo = sysInfos.get(position - userInfos.size());
        }
        return processInfo;
    }

    // 箭头向下
    private void initDownArrow() {
        ivArrow1.setImageResource(R.drawable.drawer_arrow_down);
        ivArrow2.setImageResource(R.drawable.drawer_arrow_down);
    }

    // 箭头向上
    private void initUpArrow() {
        ivArrow1.setImageResource(R.drawable.drawer_arrow_up);
        ivArrow2.setImageResource(R.drawable.drawer_arrow_up);
    }

    // 清理所有的进程
    public void cleanAll() {
        totalCleanCount = 0;
        totalCleanMemory = 0;
        // 用户进程
        for (ProcessInfo info : userInfos) {
            if (getPackageName().equals(info.processName)) {
                continue;
            }
            if (info.isChecked) {
                ProcessProvider.killBackGroundProcess(getApplicationContext(), info.processName);
                totalCleanCount++;
                totalCleanMemory += info.usedMem;
                userInfos.remove(info);
            }
        }

        if (totalCleanCount > 0) {
            Toast.makeText(getApplicationContext(),
                    "帮你清理了" + Formatter.formatFileSize(getApplicationContext(), totalCleanMemory), Toast.LENGTH_SHORT).show();
            // 刷新UI
            if (processAdapter != null) {
                processAdapter.notifyDataSetChanged();
            }
        } else {
            Toast.makeText(getApplicationContext(), "您的手机非常健康，特别是在我的守护下", Toast.LENGTH_SHORT).show();
        }
    }

    // 全选
    public void selectAll() {
        // 所有进程的进程的check设置true
        for (ProcessInfo info : userInfos) {
            if (getPackageName().equals(info.processName)) {
                continue;
            }
            info.isChecked = true;
        }

        for (ProcessInfo info : sysInfos) {
            info.isChecked = true;
        }
        // 更新UI
        if (processAdapter != null) {
            processAdapter.notifyDataSetChanged();
        }
    }

    // 反选
    public void reverseAll() {
        for (ProcessInfo info : userInfos) {
            if (getPackageName().equals(info.processName)) {
                continue;
            }
            info.isChecked = !info.isChecked;
        }

        for (ProcessInfo info : sysInfos) {
            info.isChecked = !info.isChecked;
        }
        // 更新UI
        if (processAdapter != null) {
            processAdapter.notifyDataSetChanged();
        }
    }


}
